import { reactive, computed } from 'vue'
import { Question, QuestionListVO, TagCategory, TagCategoryVO, QuestionQuery, TagQuery, DictTypes } from './data.d'
import { getQuestionList, getTagList } from './api'
import { useDict } from '@/hooks/useDict'
import { DictHooksOptions } from '@/hooks/useDict/data.d'

/**
 * 将API返回的Question对象转换为视图所需对像
 */
export const questionMapper = ({
  id,
  title,
  difficultyName,
  tagNameList,
  isVip,
  status,
}: Question): QuestionListVO => ({
  id,
  title,
  difficulty: difficultyName,
  tags: tagNameList,
  isVip,
  markedName: '❌',
})

/**
 * 将API返回的TagCategory数组转换为组件所需的TagCategoryVO数组
 */
export const tagCategoryMapper = (categories: TagCategory[]): TagCategoryVO[] => {
  return categories.map((category) => ({
    name: category.name,
    tags: category.secondCodeDuckTagList.map((tag) => tag.name),
  }))
}

/**
 * 获取题目列表数据服务
 * @param params 查询参数
 * @returns 处理后的题目列表数据
 */
export const fetchQuestionListData = async (params: QuestionQuery) => {
  try {
    const data = await getQuestionList(params)

    // 直接使用后端返回的数据，移除前端过滤逻辑
    const questionList = data.records.map((question) => questionMapper(question))

    return {
      list: questionList,
      total: data.total, // 使用后端返回的真实总数
      current: data.current,
      pages: data.pages, // 使用后端返回的页数
      size: data.size,
    }
  } catch (error) {
    console.error('获取题目列表失败:', error)
    throw error
  }
}

/**
 * 获取标签数据
 * @param params 查询参数
 * @returns 处理后的标签分类数据
 */
export const fetchTagListData = async (params: TagQuery) => {
  try {
    const data = await getTagList(params)

    // 映射
    const tagCategories = tagCategoryMapper(data.records)

    return {
      categories: tagCategories,
      total: data.total,
    }
  } catch (error) {
    console.error('获取标签数据失败:', error)
    // 如果获取失败返回默认数据
    return {
      categories: [
        { name: 'Java', tags: ['Java', 'Java 基础', 'Java 集合', 'Java并发'] },
        { name: 'C++', tags: ['C++', 'STL', 'Boost'] },
      ] as TagCategoryVO[],
      total: 2,
    }
  }
}

/**
 * 封装字典相关的所有逻辑
 */
export const useQuestionDictService = () => {
  // 字典状态管理
  const dictState: DictHooksOptions<DictTypes> = reactive({
    dictTypeList: ['question_difficulty', 'question_status', 'user_vip_flag'],
    dictMap: {} as Record<DictTypes, any[]>,
  })

  const { getDictList } = useDict(dictState)

  /**
   * 获取字典标签
   * @param dictType 字典类型
   * @param value 字典值
   * @returns 字典标签
   */
  const getDictLabel = (dictType: DictTypes, value: string): string => {
    const dictList = dictState.dictMap?.[dictType] || []
    const item = dictList.find((dict) => dict.itemValue === value)
    return item?.itemLabel || value
  }

  /**
   * 获取难度文本
   * @param difficulty 难度值
   * @returns 难度显示文本
   */
  const getDifficultyText = (difficulty?: number): string => {
    if (difficulty === undefined || difficulty === null) return '难度'

    // 优先使用字典数据
    const dictLabel = getDictLabel('question_difficulty', difficulty.toString())
    if (dictLabel !== difficulty.toString()) {
      return `难度: ${dictLabel}`
    }

    // 降级静态映射
    const staticMap: Record<string, string> = {
      '0': '难度: 简单',
      '1': '难度: 中等',
      '2': '难度: 困难',
    }
    return staticMap[difficulty.toString()] || '难度'
  }

  /**
   * 获取VIP文本
   * @param isVip VIP值
   * @returns VIP显示文本
   */
  const getVipText = (isVip?: number): string => {
    if (isVip === undefined || isVip === null) return '会员专属'

    const dictLabel = getDictLabel('user_vip_flag', isVip.toString())
    if (dictLabel !== isVip.toString()) {
      return `会员专属: ${dictLabel}`
    }

    const staticMap: Record<string, string> = {
      '1': '会员专属: 是',
      '0': '会员专属: 否',
    }
    return staticMap[isVip.toString()] || '会员专属'
  }

  /**
   * 获取标记文本
   * @param marked 标记值
   * @returns 标记显示文本
   */
  const getMarkedText = (marked?: number): string => {
    if (marked === undefined || marked === null) return '标记'

    const dictLabel = getDictLabel('question_status', marked.toString())
    if (dictLabel !== marked.toString()) {
      return `标记: ${dictLabel}`
    }

    const staticMap: Record<string, string> = {
      '0': '标记: ❌未掌握',
      '1': '标记: ✅已掌握',
      '2': '标记: ⏰晚点再刷',
    }
    return staticMap[marked.toString()] || '标记'
  }

  /**
   * 获取难度样式类名
   * @param difficulty 难度文本
   * @returns 样式类名对象
   */
  const getDifficultyClass = (difficulty: string) => {
    const difficultyStyleMap: Record<string, string> = {
      简单: 'difficulty-simple',
      中等: 'difficulty-medium',
      困难: 'difficulty-hard',
    }
    const className = difficultyStyleMap[difficulty]
    return className ? { [className]: true } : {}
  }

  const initDict = () => {
    getDictList()
  }

  return {
    dictState,
    getDictLabel,
    getDifficultyText,
    getVipText,
    getMarkedText,
    getDifficultyClass,
    initDict,
  }
}

/**
 * 难度排序提示文本生成
 * @param sortState 排序状态
 * @returns 提示文本
 */
export const getDifficultyTooltipText = (sortState: 'asc' | 'desc' | null): string => {
  if (sortState === null) {
    return '点击升序排列'
  } else if (sortState === 'asc') {
    return '点击降序排列'
  } else {
    return '点击升序排列'
  }
}
